import base64

import requests
from PIL.Image import Image
from flask import Blueprint, request, render_template, jsonify, current_app, url_for, send_from_directory, g, abort, redirect,flash
from werkzeug.utils import secure_filename
import os

from forms.user import LoginForm
from models.post import PostModel, BoardModel, CommentModel, PlantBoardModel, PlantPostModel
from exts import csrf, db
from decorators import login_required
from forms.post import PublicPostForm, PublicCommentForm,PublicSearchForm
from utils import restful
from flask_paginate import Pagination
from sqlalchemy import or_, func

bp = Blueprint("image", __name__, url_prefix="")

# 请替换为你自己的 API Key 和 Secret Key
API_KEY = 'eEYet3uajVq2NnF9ItrHRrSa'
SECRET_KEY = 'aUBfGldd0axzD201XDDZXiivtU8Jb8dJ'

def get_access_token():
    url = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRET_KEY}'
    response = requests.get(url)
    if response.status_code == 200:
        return response.json().get('access_token')
    return None

@bp.route('/plant_detect', methods=['GET', 'POST'])
def image_detect():
    if request.method == 'POST':
        file = request.files['image']
        if file:
            img = file.read()
            img_base64 = base64.b64encode(img).decode('utf-8')
            access_token = get_access_token()
            if access_token:
                api_url = f'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token={access_token}'
                headers = {'Content-Type': 'application/x-www-form-urlencoded'}
                data = {'image': img_base64}
                response = requests.post(api_url, headers=headers, data=data)
                current_app.logger.info("image_detect页面被请求了")
                if response.status_code == 200:
                    result = response.json()
                    animals = result.get('result', [])
                    current_app.logger.info(animals[0])
                    return render_template('front/image_detect.html', animals=[animals[0]]) # animaals为字典列表，animals[0]为字典，需要加[]变成列表
    #current_app.logger.info("image_detect页面被请求了")
    return render_template('front/image_detect.html')